/*
 * ReceiveThread.cpp
 *
 *  Created on: Nov 15, 2014
 *      Author: toti
 */

#include <Threads/ReceiveThread.hpp>

ReceiveThread::ReceiveThread(TCPConnection *tcpConnection){

	this->tcpConnection = tcpConnection;

	/* Start new thread */
	pthread_create(&thread, 0, ReceiveThread::startThread, (void*)this);

	ofs = new std::ofstream(Config::instance()->getOutputFile());
}

void *ReceiveThread::startThread(void* object){

	/* Cast argument to ReceiveThread */
	ReceiveThread *receiveThread = (ReceiveThread*)object;

	/* Execute the thread routine */
	receiveThread->run();

	/* If this position is reached, the former session has been closed */
	delete(receiveThread);

	return 0;
}


void ReceiveThread::run(){

	while(true){

		char input;
		std::string result;

		do{

			tcpConnection->receiveData(&input, 1);

			/* Check if an error occured */
			if(tcpConnection->isConnected()){
				result.append(&input,1);
			}else{
				exit(0);
			}

		}while(input != 0);


		(*ofs) << result;
		ofs->flush();

		result.assign("");

	}

}

void ReceiveThread::registerReceiveCallback(IReceiveCallback *receiveCallback){


}
